package com.lvmama.dest.schedule.common;

import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;

import com.lvmama.dest.schedule.utils.StringUtil;



/**
 * @author Alex
 *
 */
public class SpringBeanProxy {

	private static ApplicationContext applicationContext;
	
	public synchronized static void setApplicationContext(ApplicationContext arg0) {
		applicationContext = arg0;
	}
	
    /**
     * 获取bean的方法 
     * @param <T>
     * @param clazz
     * @param beanName
     * @return
     */
    public static <T> T getBean(Class<T> clazz){
    	Object o = applicationContext.getBean(clazz);
    	if(o!=null){
    		return clazz.cast(o);
    	}
    	return null;
    }
    
   
	
	public static Object getBean(String beanName){
		return applicationContext.getBean(beanName);
	}
	
	
	/**
	 * 检查容器中是否包含已知bean
	 * @param beanName
	 */
	public static boolean containsBean(String beanName){
		return applicationContext.containsBean(beanName);
	}
	/**
	 * 动态添加BEAN
	 * @param beanName
	 * @param beanClass
	 */
	public static Object addBeanService(String beanName,Class<?> beanClass) {
		if(StringUtil.isEmptyString(beanName)){
			return null;
		}
		if (!applicationContext.containsBean(beanName)) {
			Class<?> serviceClass = beanClass;
			BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(serviceClass);
			registerBean(beanName, beanDefinitionBuilder.getRawBeanDefinition());
		}
		return SpringBeanProxy.getBean(beanName);
	}
	/**
	 * 向spring容器注册bean
	 * @param beanName
	 * @param beanDefinition
	 */
	private static void registerBean(String beanName, BeanDefinition beanDefinition) {
		ConfigurableApplicationContext configurableApplicationContext = (ConfigurableApplicationContext) applicationContext;
		BeanDefinitionRegistry beanDefinitonRegistry = (BeanDefinitionRegistry) configurableApplicationContext
				.getBeanFactory();
		beanDefinitonRegistry.registerBeanDefinition(beanName, beanDefinition);
	}
}